﻿
namespace IMath
{
    public interface IMathCalculator
    {
        int Add(int a, int b); 
        int Subtract(int a, int b); 
        int Multiply(int a, int b); 
        double Divide(int a, int b); 
    }
}

namespace Math
{
    
    public class MathCalculator : IMathCalculator
    {
        public int Add(int a, int b) => a + b;

        public int Subtract(int a, int b) => a - b;

        public int Multiply(int a, int b) => a * b;

        public double Divide(int a, int b)
        {
            if (b == 0) throw new DivideByZeroException("除数不能为0");
            return (double)a / b;
        }
    }
}


namespace ReflectionMathDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("===== 反射技术调用数学计算接口 =====");

            try
            {
                string mathDllPath = @"C:\Path\To\Math\bin\Debug\net6.0\Math.dll"; 
                Assembly mathAssembly = Assembly.LoadFrom(mathDllPath);

              
                Type calculatorType = mathAssembly.GetType("Math.MathCalculator");
                IMathCalculator calculator = (IMathCalculator)Activator.CreateInstance(calculatorType);

             
                Console.WriteLine("\n=== 直接调用接口方法 ===");
                TestCalculator(calculator);

                Console.WriteLine("\n=== 反射调用接口方法 ===");
                TestCalculatorByReflection(calculatorType, calculator);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误：{ex.Message}");
            }

            Console.ReadKey();
        }

      
        static void TestCalculator(IMathCalculator calculator)
        {
            int a = 10, b = 3;
            Console.WriteLine($"{a} + {b} = {calculator.Add(a, b)}");
            Console.WriteLine($"{a} - {b} = {calculator.Subtract(a, b)}");
            Console.WriteLine($"{a} × {b} = {calculator.Multiply(a, b)}");
            Console.WriteLine($"{a} ÷ {b} = {calculator.Divide(a, b):F2}");
        }

       
        static void TestCalculatorByReflection(Type calculatorType, object calculatorInstance)
        {
            int a = 20, b = 4;
        
            MethodInfo addMethod = calculatorType.GetMethod("Add", new[] { typeof(int), typeof(int) });
            object addResult = addMethod.Invoke(calculatorInstance, new object[] { a, b });
            Console.WriteLine($"{a} + {b} = {addResult}");

      
            MethodInfo divideMethod = calculatorType.GetMethod("Divide", new[] { typeof(int), typeof(int) });
            object divideResult = divideMethod.Invoke(calculatorInstance, new object[] { a, b });
            Console.WriteLine($"{a} ÷ {b} = {divideResult:F2}");
        }
    }
}